import { PrismaClient } from '@prisma/client';
import { generateUniqueSlug } from '../utils/slug';
import type {
  CreateCaseRequest,
  UpdateCaseRequest,
  CaseQueryParams,
  CaseListResponse,
  CaseWithCategory,
  CaseStats,
  CreateCaseCategoryRequest,
  UpdateCaseCategoryRequest,
  CaseCategory
} from '../types/case';

const prisma = new PrismaClient();

export class CaseService {
  async createCase(data: CreateCaseRequest, userId?: number): Promise<CaseWithCategory> {
    const existingSlugs = await this.getExistingSlugs();
    const slug = generateUniqueSlug(existingSlugs);

    const caseData = await prisma.case.create({
      data: {
        title: data.title,
        slug,
        content: data.content,
        summary: data.summary,
        author: data.author,
        categoryId: data.categoryId,
        status: data.status,
        coverImage: data.coverImage,
        tags: data.tags || [],
        isTop: data.isTop || false,
        isRecommend: data.isRecommend || false,
        publishedAt: data.status ? new Date() : null,
        userId: userId
      } as any,
      include: {
        category: true
      }
    });

    return caseData as unknown as CaseWithCategory;
  }

  async getCaseById(id: number): Promise<CaseWithCategory | null> {
    const caseData = await prisma.case.findFirst({
      where: {
        id,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true
      }
    });

    if (caseData) {
      // 增加浏览量
      await prisma.case.update({
        where: { id },
        data: { views: { increment: 1 } }
      });
    }

    return caseData as CaseWithCategory | null;
  }

  async getCaseBySlug(slug: string): Promise<CaseWithCategory | null> {
    const caseData = await prisma.case.findFirst({
      where: {
        slug,
        display: true, // 只显示未软删除的数据
      },
      include: {
        category: true
      }
    });

    if (caseData) {
      // 增加浏览量
      await prisma.case.update({
        where: { slug },
        data: { views: { increment: 1 } }
      });
    }

    return caseData as CaseWithCategory | null;
  }

  async getCases(params: CaseQueryParams = {}): Promise<CaseListResponse> {
    const {
      page = 1,
      limit = 10,
      categoryId,
      status,
      keyword,
        userId,
      isTop,
      isRecommend,
      sort = 'latest'
    } = params;

    const skip = (page - 1) * limit;

    // 构建查询条件
    const where: any = {
      display: true, // 只显示未软删除的数据
    };

    if (categoryId) {
      where.categoryId = categoryId;
    }

    if (status !== undefined) {
      where.status = status;
    }

    if (isTop !== undefined) {
      where.isTop = isTop;
    }

    if (isRecommend !== undefined) {
      where.isRecommend = isRecommend;
    }

    if (userId) {
      where.userId = userId;
    }

    if (keyword) {
      where.OR = [
        { title: { contains: keyword, mode: 'insensitive' } },
        { content: { contains: keyword, mode: 'insensitive' } },
        { summary: { contains: keyword, mode: 'insensitive' } }
      ];
    }

    // 构建排序条件
    let orderBy: any = {};
    switch (sort) {
      case 'latest':
        orderBy = { createdAt: 'desc' };
        break;
      case 'popular':
        orderBy = { views: 'desc' };
        break;
      case 'likes':
        orderBy = { likes: 'desc' };
        break;
      default:
        orderBy = { createdAt: 'desc' };
    }

    // 执行查询
    const [cases, total] = await Promise.all([
      prisma.case.findMany({
        where,
        skip,
        take: limit,
        orderBy,
        include: {
          category: true,
          user: true
        }
      }),
      prisma.case.count({ where })
    ]);

    const totalPages = Math.ceil(total / limit);

    return {
      cases: cases as CaseWithCategory[],
      total,
      page,
      limit,
      totalPages
    };
  }

  async updateCase(id: number, data: UpdateCaseRequest): Promise<CaseWithCategory> {
    const updateData: any = { ...data };

    // 如果状态从草稿变为发布，设置发布时间
    if (data.status === true) {
      const existingCase = await prisma.case.findUnique({ where: { id } });
      if (existingCase && !existingCase.publishedAt) {
        updateData.publishedAt = new Date();
      }
    }

    const caseData = await prisma.case.update({
      where: { id },
      data: updateData,
      include: {
        category: true
      }
    });

    return caseData as unknown as CaseWithCategory;
  }

  async deleteCase(id: number, deleteBy?: number): Promise<void> {
    await prisma.case.update({
      where: { id },
      data: {
        display: false,
        deleteBy: deleteBy || null,
        deleteAt: new Date(),
      }
    });
  }

  async getCaseStats(): Promise<CaseStats> {
    const [total, published, draft, top, recommend] = await Promise.all([
      prisma.case.count({ where: { display: true } }),
      prisma.case.count({ where: { status: true, display: true } }),
      prisma.case.count({ where: { status: false, display: true } }),
      prisma.case.count({ where: { isTop: true, display: true } }),
      prisma.case.count({ where: { isRecommend: true, display: true } })
    ]);

    return {
      total,
      published,
      draft,
      top,
      recommend
    };
  }

  async getRecommendCases(limit: number = 5): Promise<CaseWithCategory[]> {
    const cases = await prisma.case.findMany({
      where: {
        status: true,
        isRecommend: true,
        display: true, // 只显示未软删除的数据
      },
      take: limit,
      orderBy: { createdAt: 'desc' },
      include: {
        category: true
      }
    });

    return cases as CaseWithCategory[];
  }

  async getTopCases(limit: number = 3): Promise<CaseWithCategory[]> {
    const cases = await prisma.case.findMany({
      where: {
        status: true,
        isTop: true,
        display: true, // 只显示未软删除的数据
      },
      take: limit,
      orderBy: { createdAt: 'desc' },
      include: {
        category: true
      }
    });

    return cases as CaseWithCategory[];
  }

  private async getExistingSlugs(): Promise<string[]> {
    const cases = await prisma.case.findMany({
      select: { slug: true }
    });
    return cases.map(c => c.slug);
  }

  // 案例分类相关方法
  async getAllCaseCategories(): Promise<CaseCategory[]> {
    const categories = await prisma.caseCategory.findMany({
      where: { status: true },
      orderBy: { sort: 'desc' }
    });

    return categories as CaseCategory[];
  }

  async getCaseCategoryById(id: number): Promise<CaseCategory | null> {
    const category = await prisma.caseCategory.findUnique({
      where: { id }
    });

    return category as CaseCategory | null;
  }

  async createCaseCategory(data: CreateCaseCategoryRequest): Promise<CaseCategory> {
    const category = await prisma.caseCategory.create({
      data: {
        name: data.name,
        description: data.description,
        sort: data.sort || 0
      }
    });

    return category as CaseCategory;
  }

  async updateCaseCategory(id: number, data: UpdateCaseCategoryRequest): Promise<CaseCategory> {
    const category = await prisma.caseCategory.update({
      where: { id },
      data
    });

    return category as CaseCategory;
  }

  async deleteCaseCategory(id: number): Promise<void> {
    await prisma.caseCategory.delete({
      where: { id }
    });
  }
} 